import Vue from 'vue'
import VueRouter from 'vue-router'

import { getToken } from '@/utils/storage'
import { Toast } from 'vant'

const Login = () => import('@/views/one-level-router/Login')
const Layout = () => import('@/views/one-level-router/Layout')
const Detail = () => import('@/views/one-level-router/Detail')
const Home = () => import('@/views/two-level-router/Home')
const Questions = () => import('@/views/two-level-router/Questions')
const Video = () => import('@/views/two-level-router/Video')
const User = () => import('@/views/two-level-router/user/User')
const UserProfile = () => import('@/views/two-level-router/user/profile/Profile')

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  { path: '/detail/:id', component: Detail },
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/home', component: Home },
      { path: '/questions', component: Questions },
      {
        path: '/user',
        component: User
        // children: [
        // ]
      },
      { path: '/video', component: Video }
    ]
  },

  { path: '/user/profile', component: UserProfile }
]

const router = new VueRouter({
  routes
})

const whileList = ['/login', '/home']
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    next()
  } else {
    if (whileList.includes(to.path)) {
      next()
    } else {
      Toast.fail('请登录')
      next('/login')
    }
  }
})

export default router
